package com.shenmazong.demoesserver.service.impl;

import com.shenmazong.demoesserver.pojo.TbPerson;
import com.shenmazong.demoesserver.repo.MyElasticRepository;
import com.shenmazong.demoesserver.service.TbPersonService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

@Service
public class TbPersonServiceImpl implements TbPersonService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Autowired
    private MyElasticRepository elasticRepository;

    @Override
    public void createIndex(String indexName) {
        elasticsearchTemplate.indexOps(IndexCoordinates.of(new String[]{indexName})).create();
    }

    @Override
    public void createIndex(Class<?> clazz) {
        //elasticsearchTemplate.indexOps(clazz).create();
        elasticsearchTemplate.indexOps(clazz);
    }

    @Override
    public void deleteIndex(String indexName) {
        elasticsearchTemplate.indexOps(IndexCoordinates.of(new String[]{indexName})).delete();
    }

    @Override
    public void deleteIndex(Class<?> clazz) {
        elasticsearchTemplate.indexOps(clazz).delete();
    }

    @Override
    public void save(TbPerson person) {
        elasticRepository.save(person);
    }

    @Override
    public void saveAll(List<TbPerson> list) {
        elasticRepository.saveAll(list);
    }

    @Override
    public Iterator<TbPerson> findAll() {
        return elasticRepository.findAll().iterator();
    }


    @Override
    public Iterator<TbPerson> findAll(String keyWord) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(matchQuery("name", "华为"))
                .build();
        SearchHits<TbPerson> persons = elasticsearchTemplate.search(searchQuery, TbPerson.class);

        System.out.println("搜到:"+persons.getSearchHits().size());

        for(SearchHit<TbPerson> hit:persons.getSearchHits()) {
            TbPerson p = hit.getContent();
            System.out.println(p);

            System.out.println("score="+hit.getScore());
            System.out.println("id="+hit.getId());
        }
        return null;
    }
}
